package com.kgar.util;

import cn.hutool.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class ResumeParseUtil {

    public static JSONObject resumeParser(String fname, byte[] bytes, String url, String appcode) throws Exception {
        // 设置头字段
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "APPCODE " + appcode);
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.addHeader("Content-Type", "application/json");

        // 读取简历内容
        String data = new String(Base64.encodeBase64(bytes), Consts.UTF_8);

        // 设置内容信息
        JSONObject json = new JSONObject();
        Map<String, Object> map = new HashMap<>();
        map.put("file_name", fname);    // 文件名
        map.put("file_cont", data);    // 经base64编码过的文件内容
        map.put("need_avatar", 0);        // 是否需要解析头像
        map.put("ocr_type", 1);        // 1为高级ocr
        json.putAll(map);
        StringEntity params = new StringEntity(json.toString(), Consts.UTF_8);
        httpPost.setEntity(params);

        // 发送请求
        HttpClient httpclient = HttpClientBuilder.create().build();
        HttpResponse response = httpclient.execute(httpPost);

        // 处理返回结果
        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);

        JSONObject res = new JSONObject(resCont);
        System.out.println(res);

        return res;
    }

    public static void main(String[] args) throws Exception {
        String url = "http://resumesdk.market.alicloudapi.com/ResumeParser";
        String fname = "D:/resumeSDK/test_files/yaoming.doc";    //替换为你的文件名
        String appcode = "你的appcode";

        File file = new File(fname);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {

            resumeParser(file.getName(), fileInputStream.readAllBytes(), url, appcode);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

    }
}
